package cn.com.iresearch.android.componentizationsupporter

import android.content.Context
import android.content.pm.PackageManager


/**
 * 组件化支持者,路由
Created By: Seal.Wu
Date: 2018/4/3
Time: 10:37
 */
object ComponentRouter {
    private var hasBeenInit = false

    fun init(context: Context) {
        val applicationInfo = context.applicationContext.packageManager
                .getApplicationInfo(context.packageName,
                        PackageManager.GET_META_DATA)

        applicationInfo.metaData.keySet().forEach {
            if (it.startsWith("IRComponent")) {
                val componentClassName = applicationInfo.metaData.get(it).toString()
                val component = Class.forName(componentClassName).newInstance()
                if (component is IComponent) {
                    ComponentManager.registerComponent(component = component)
                }
            }
        }
        hasBeenInit = true
    }


    fun getComponent(componentName: String): IComponent {
        if (hasBeenInit.not()) {
            throw IllegalStateException("${this::class.java.name} 没有被初初始化！请先执行 init(context:Context) 方法！")
        }
        return ComponentManager.getComponent(componentName)
    }
}